package com.shanshi.activity.service;


import android.app.IntentService;
import android.content.Intent;
import android.util.Log;

import com.shanshi.activity.tool.OkHttpTool;

import java.io.File;
import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class SuggestService extends IntentService {

	// 参数类型
	private static final MediaType MEDIA_TYPE_PNG = MediaType.parse("image/png");
	// 创建OkHttpClient实例
	private final OkHttpClient client = new OkHttpClient();

	public SuggestService() {
		super("SuggestService");
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		// 通过intent获取主线程传来的数据
		int storeId = intent.getIntExtra("storeId", 0);
		int userId = intent.getIntExtra("userId",0);
		String content = intent.getStringExtra("content");
		Log.e("content =", content);
		String uri1 = intent.getStringExtra("uri1");
		String uri2 = intent.getStringExtra("uri2");
		String uri3 = intent.getStringExtra("uri3");

//		MultipartBuilder builder = new MultipartBuilder().type(MultipartBuilder.FORM);
		MultipartBody.Builder builder=  new MultipartBody.Builder().setType(MultipartBody.FORM);
//		// 遍历map中所有参数到builder
//
		builder.addFormDataPart("userId", userId+"");
		builder.addFormDataPart("content", content);
		if(uri1!=""){
			builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri1)));
		}
		if(uri2!=""){
			builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri2)));
		}
		if(uri3!=""){
			builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"imgFiles\";filename=\"file.jpg\""), RequestBody.create(MediaType.parse("image/jpg"),new File(uri3)));
		}

		// 构建请求体
		RequestBody requestBody = builder.build();

		// 构建请求
		Request request = new Request.Builder()
				.url(OkHttpTool.BASE_URL+"stores/" + storeId + "/advice")// 地址
				.post(requestBody)// 添加请求体
				.build();

		// 发送异步请求，同步会报错，Android4.0以后禁止在主线程中进行耗时操作

		client.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Call arg0, IOException arg1) {
				// TODO Auto-generated method stub
				System.out.println("request = " + arg0.toString());
				System.out.println("e.getLocalizedMessage() = " + arg1.getLocalizedMessage());
			}

			@Override
			public void onResponse(Call arg0, Response arg1) throws IOException {
				// TODO Auto-generated method stub
				Log.e("response =", arg1.body().string());
			}
		});

	}
	

}
